package io.vertx.kue.example

import io.vertx.kue.Kue
import io.vertx.kue.queue.*
import io.vertx.core.AbstractVerticle
import io.vertx.core.Handler
import io.vertx.core.json.JsonObject

/**
 * Vert.x Blueprint - Job Queue
 * Example - A delayed email processing verticle
 * This example shows the delayed jobs
 *
 * @author Eric Zhao
 */
class DelayedEmailVerticle : AbstractVerticle() {

    @Throws(Exception::class)
    override fun start() {
        // create our job queue
        val kue = Kue.createQueue(vertx, config())

        val data = JsonObject()
                .put("title", "Account renewal required")
                .put("to", "qinxin@jianpo.xyz")
                .put("template", "renewal-email")

        // create a delayed email job
        val email = kue.createJob("email", data)
                .setDelay(8888)
                .priority(Priority.HIGH)
                .onComplete(Handler{ println("renewal job completed") })

        kue.createJob("email", JsonObject().put("title", "Account expired")
                .put("to", "qinxin@jianpo.xyz")
                .put("template", "expired-email"))
                .setDelay(26666)
                .priority(Priority.HIGH)
                .save() // save job
                .compose({ email.save() }) // save another job
                .setHandler({ sr ->
                    if (sr.succeeded()) {
                        // process emails
                        kue.processBlocking("email", 10, Handler{ job ->
                            vertx.setTimer(2016) { job.done() } // cost 2s to process
                        })
                    } else {
                        sr.cause().printStackTrace()
                    }
                })
    }

}
